package com.jugheadzhou.core.zk;

import com.jugheadzhou.core.zk.helper.IPUtil;
import com.jugheadzhou.core.zk.helper.MythServiceLeaderLatchHelper;
import com.jugheadzhou.core.zk.helper.MythServiceRegistryHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@Configuration 
@ConditionalOnClass(CuratorFramework.class)
@EnableConfigurationProperties(ZkProperties.class)
@Slf4j
public class ServiceRegistryAutoConffiguration {
	
	@Value("${spring.application.name}")
	String applicationName;
	
	//@LocalServerPort
	@Value("${server.port}")
	int port;
	
	@ConditionalOnProperty(ZkProperties.PROPERTY_PATH_CONNECT)
	@Bean(name="zkClient")
	public ZkClient zkClient(ZkProperties zkProperties) throws Exception {
		if(StringUtils.isEmpty(zkProperties.getServiceName())) {
			zkProperties.setServiceName(applicationName);
		}
		ZkClient client = new ZkClient(zkProperties);	
		log.info("create zk client: root={}, name={}", client.getZkProps().getNamespace(), client.getZkProps().getServiceName());
		return 	client;
	}

	@ConditionalOnProperty(name=ZkProperties.PROPERTY_PATH + ".enableRegistry", havingValue="1")
	@ConditionalOnBean(ZkClient.class)
	@Bean(name="mythServiceRegistryHelper")
	public MythServiceRegistryHelper mythServiceRegistryHelper(ZkClient zkClient) throws Exception {
		
		MythServiceRegistryHelper helper  =new MythServiceRegistryHelper(zkClient, IPUtil.getRealIp(), port+"");
		helper.registerInstance(true,null);
		log.info("registry service : service={}, instance={}", helper.getRegistryServiceId(), helper.getRegistryInstanceName());
		return helper;
	}
	
	@ConditionalOnProperty(name=ZkProperties.PROPERTY_PATH + ".enableLeader", havingValue="1")
	@ConditionalOnBean(ZkClient.class)
	@Bean(name="mythServiceLeaderLatchHelper")
	public MythServiceLeaderLatchHelper mythServiceLeaderLatchHelper(ZkClient zkClient) throws Exception {
		MythServiceLeaderLatchHelper helper = new MythServiceLeaderLatchHelper(zkClient, IPUtil.getRealIp(), port+"");
		log.info("registry latcher of service leader");
		return helper;
	}
}
